"""
URL configuration for zzsadmin project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.views.generic import RedirectView
from tencent_map.views import MapSearchView, PublicMapSearchView  # 导入地图搜索视图

import json

# AJAX登录视图
@csrf_exempt
@require_http_methods(["POST"])
def ajax_login(request):
    """
    处理前端AJAX登录请求
    """
    try:
        # 获取用户名和密码
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
        
        if not username or not password:
            return JsonResponse({
                'success': False,
                'error': '用户名和密码不能为空'
            }, status=400)
        
        # 验证用户
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            if user.is_active:
                login(request, user)
                return JsonResponse({
                    'success': True,
                    'message': '登录成功',
                    'user': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'is_staff': user.is_staff,
                        'is_superuser': user.is_superuser,
                    }
                })
            else:
                return JsonResponse({
                    'success': False,
                    'error': '账户已被禁用'
                }, status=403)
        else:
            return JsonResponse({
                'success': False,
                'error': '用户名或密码错误'
            }, status=401)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'error': '请求数据格式错误'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'登录失败: {str(e)}'
        }, status=500)

urlpatterns = [
    path('', RedirectView.as_view(url='/admin/')),  # 将根路径重定向到 /admin/
    path('admin/', admin.site.urls),
    
    # AI模块 - 统一使用api/前缀
    # 注意：更具体的路径应该放在前面，避免路由冲突
    path('api/', include('ai_video.urls')),  # AI视频生成API
    path('api/', include('ai_image.urls')),  # AI图像生成API
    path('api/', include('ai_music.urls')),  # AI音乐生成API
    path('api/', include('ai_text.urls')),   # AI文本生成API
    path('api/', include('ai_app.urls')),    # AI应用管理API,
    
    # 其他模块
    path('api/tencent-map/', include('tencent_map.urls')),  # 腾讯地图API接口（供前端直接调用）
    
    # 直接的API搜索接口（供前端调用，路径为/api/search/）
    path('api/search/', PublicMapSearchView.as_view(), name='api_search_direct'),
    
    # Django内置认证系统
    path('accounts/', include('django.contrib.auth.urls')),
    
    # AJAX登录API
    path('api/auth/login/', ajax_login, name='ajax_login'),
    
    # 根路径重定向到管理后台
    # path('', admin.site.urls),  # 注释掉重复的admin路径
]

# 在开发环境中提供媒体文件服务
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)